package com.ruoyi.framework.security.filter;



import com.ruoyi.framework.constant.JwtClaimsConstant;
import com.ruoyi.framework.context.BaseContext;
import com.ruoyi.framework.properties.JwtProperties;
import com.ruoyi.framework.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class JwtUserTokenFilter implements Filter {
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Filter初始化时调用
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("================启动PE的过滤器成功================");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        // 获取请求的URI
        String uri = httpServletRequest.getRequestURI();
        log.info(uri);
        // 检查是否是登录请求，如果是，则直接放行
        if (uri.endsWith("/user/login")||uri.endsWith("/user/register")||uri.contains("/doctor")) {
            chain.doFilter(request, response);
            return;
        }

        //1、从请求头中获取令牌
        String token = httpServletRequest.getHeader(jwtProperties.getUserTokenName());

        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前用户id：", userId);
            BaseContext.setCurrentId(userId); //将当前登录用户id存入线程
            //3、通过，放行
            chain.doFilter(request, response);
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            httpServletResponse.setStatus(401);
            httpServletResponse.getWriter().write("请登录");
        }
    }

    @Override
    public void destroy() {
        // Filter销毁时调用
    }
}
